/*
 * Copyright 2011 Clean GWT
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cleangwt.bootstrap.template.client;

import java.util.List;

import com.cleangwt.bootstrap.client.ui.Navbar;
import com.cleangwt.bootstrap.client.ui.PageNavigator;
import com.cleangwt.user.shared.Link;
import com.cleangwt.user.shared.Links;
import com.google.gwt.user.client.ui.Widget;

/**
 * A {@link NavbarSidebarContainer} with a fixed-top {@link Navbar} that contains a top navigator.
 * And each navigator item may link to a {@link Sidebar} for sub navigations.
 * 
 * @author Jess
 * @version 1.0
 * @since 1.0
 */
public class NavbarSidebarContainer1 extends NavbarSidebarContainer {

  protected PageNavigator topNavigator = new PageNavigator();
  private Sidebar[] sidebars;
  protected Link activeRoot;

  /**
   * Creates a navbar-sidebar page container with the given links.
   * 
   * @param navbarStyle the navbar's type style
   * @param links the links
   */
  public NavbarSidebarContainer1(String navbarStyle, List<Link> links) {
    super(navbarStyle, links);
    this.topNavigator.setLinks(Links.linkToLeaves(links));
    this.sidebars = new Sidebar[topNavigator.getItemCount()];
    getNavbar().addNavigator(topNavigator);
  }

  @Override
  public void setContentPage(String pageName, Widget page) {
    super.setContentPage(pageName, page);
    setActivePage(pageName);
    int index = topNavigator.getActiveItemIndex();
    if (index > -1 && this.activeRoot.getSubLinks() != null) {
      if (sidebars[index] == null) {
        sidebars[index] = new Sidebar(activeRoot.getSubLinks());

        sidebars[index].addCloseHandler(toggleHandler);
        sidebars[index].addOpenHandler(toggleHandler);
      }
      sidebarContainer.setWidget(sidebars[index]);
      sidebars[index].setActivePage(pageName);
      // update open state
      if (sidebars[index].isOpen()) {
        openSidebar();
      } else {
        closeSidebar();
      }
    } else {
      closeSidebar();
      sidebarContainer.setWidget(null);
    }

  }

  private void setActivePage(String pageName) {
    activeRoot = Links.getRoot(links, pageName);
    if (activeRoot != null) {
      topNavigator.setActivePage(Links.getDeafultLeaf(activeRoot).getValue());
    } else {
      topNavigator.setActivePage(null);
    }

  }
}
